package com.neusoft.controller;

import com.neusoft.base.BaseController;
import com.neusoft.config.CacheObj;
import com.neusoft.model.ItemSearch;
import com.neusoft.po.Item;
import com.neusoft.po.Price;
import com.neusoft.service.ItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;


/**
 * 商品请求控制器
 *
 * @author Lucifer
 * @since 2021/5/15 上午8:12
 */
@RestController
@RequestMapping("/item")
@Api(tags = "商品接口")
public class ItemController extends BaseController {

    @Resource
    private ItemService itemService;

    @PostMapping("/list")
    @ApiOperation(value = "商品集合")
    public List<Item> listAll(@RequestBody ItemSearch itemSearch) {
        return itemService.list(itemSearch);
    }

    @PostMapping("/banner")
    @ApiOperation(value = "商品banner")
    public List<Item> banner() {
        return itemService.banner();
    }

    @PostMapping("/page")
    @ApiOperation("商品分页数据")
    public Object page(@RequestBody ItemSearch itemSearch) {
        return itemService.page(itemSearch);
    }

    @GetMapping
    @ApiOperation("单个商品数据带评论信息、打折信息、满减信息、分类信息")
    @ApiImplicitParam(value = "商品ID", name = "id", required = true)
    public Item get(Integer id) {
        return itemService.getWithComments(id);
    }

    @PostMapping
    @ApiOperation("单个商品保存（新增，修改同）")
    public Integer save(@RequestBody Item item) {
        itemService.save(item);
        return item.getId();
    }

    @DeleteMapping("/{ids}")
    @ApiOperation("批量商品删除")
    public Integer delete(@PathVariable("ids") Integer[] ids) {
        return itemService.delete(ids);
    }

    @PostMapping("/upload")
    @ApiOperation("图片上传:返回路径-用于给item的url赋值")
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file) {
        String name = file.getOriginalFilename();
        String suffix = name.substring(name.lastIndexOf("."));
        name = System.currentTimeMillis() + suffix;
        File image = new File(CacheObj.image_dir, name);
        try {
            file.transferTo(image);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image.getAbsolutePath();
    }

    @PostMapping("/price")
    @ApiOperation("计算一组商品总价（购物车，订单都可调用）")
    public Price price(@RequestBody Integer[] item_ids) {
        return null;
    }
}
